package org.aplikator.server.descriptor;

import org.aplikator.client.shared.descriptor.ApplicationDTO;
import org.aplikator.server.persistence.PersisterFactory;
import org.aplikator.server.util.Configurator;

import com.typesafe.config.ConfigValue;

import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;


public class Application {

    // singleton
    private static Application instance = instance();

    private static Application instance() {



        @SuppressWarnings("rawtypes")
        Class clazz;
        try {
            clazz = Class.forName(Configurator.get().getConfig().getString(Configurator.STRUCTURE));
        } catch (ClassNotFoundException e) {
            throw new IllegalStateException(e);
        }
        try {
            return (Application) clazz.newInstance();
        } catch (InstantiationException e) {
            throw new IllegalStateException(e);
        } catch (IllegalAccessException e) {
            throw new IllegalStateException(e);
        }
    }

    public static Application get() {
        return instance;
    }


    private List<Menu> menus = new ArrayList<Menu>();

    private boolean showNavigation = true;

    private String defaultActionToken = null;




    protected Application() {
    }

    public Application addMenu(Menu menu) {
        menus.add(menu);
        return this;
    }

    public void setShowNavigation(boolean showNavigation) {
        this.showNavigation = showNavigation;
    }


    public void setDefaultAction(String defaultAction) {
        this.defaultActionToken = defaultAction;
    }



    public ApplicationDTO getApplicationDTO(org.aplikator.server.Context ctx){
        ApplicationDTO retval = new ApplicationDTO();
        for (Menu m: menus){
            retval.addMenu(m.getMenuDTO(ctx));
        }
        retval.setBrand(Configurator.get().getLocalizedString(Configurator.BRAND,ctx.getUserLocale()));
        retval.setShowNavigation(showNavigation);
        retval.setDefaultAction(defaultActionToken);
        Set<Entry<String, ConfigValue>> configSet = Configurator.get().getConfig().entrySet();
        for (Entry<String,ConfigValue> entry : configSet) {
            if (entry.getKey().startsWith("aplikator")){
        	    retval.setConfigString(entry.getKey(), entry.getValue().render());
            }
        }
        return retval;
    }




    public String generateDDL(boolean updateDB, boolean checkDB) {
        return PersisterFactory.getPersister().generateDDL(updateDB, checkDB);

    }
}
